package com.jxbeidou.gateway.service.impl;

import cn.hutool.captcha.ShearCaptcha;
import com.jxbeidou.core.cache.CacheService;
import com.jxbeidou.core.constents.CacheKeys;
import com.jxbeidou.core.entity.R;
import com.jxbeidou.gateway.entity.CaptchaVO;
import com.jxbeidou.gateway.service.ValidateCodeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.UUID;

/**
 * 验证码实现处理
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class ValidateCodeServiceImpl implements ValidateCodeService
{

    @Resource
    private CacheService cacheService;

    @Resource
    private ShearCaptcha shearCaptcha;

    /**
     * 生成验证码
     */
    @Override
    public R<CaptchaVO> createCaptcha() {
        try {
            shearCaptcha.createCode();
            String createText = shearCaptcha.getCode();
            log.debug("验证码：[{}]", createText);
            String captchaKey = UUID.randomUUID().toString();
            CaptchaVO captchaVO = new CaptchaVO();
            cacheService.set(CacheKeys.getCaptchaKey(captchaKey), createText, Duration.ofMinutes(2L));
            captchaVO.setKey(captchaKey);
            captchaVO.setImg(shearCaptcha.getImageBase64Data());
            return R.success(captchaVO);
        } catch (Exception e) {
            return R.failed("验证码生成失败");
        }
    }

    @Override
    public R<String> checkCaptcha(String key, String value) {
        if (StringUtils.isEmpty(value)) {
            return R.failed400("验证码不能为空");
        }
        if (StringUtils.isEmpty(key)) {
            return R.failed400("验证码已失效");
        }
        String captcha = cacheService.get(CacheKeys.getCaptchaKey(key), String.class);
        cacheService.del(CacheKeys.getCaptchaKey(key));
        if (StringUtils.isEmpty(captcha)) {
            return R.failed400("验证码已失效");
        }
        if (value.equalsIgnoreCase(captcha)) {
            return R.success("验证通过");
        }
        return R.failed400("验证码输入错误");
    }
}
